<template>
  <div class="upload">
    <el-upload
      :class="showButton ? '' : 'upload-container'"
      :action="action"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :accept="accept"
      :headers="headers"
    >
      <slot name="button" v-if="showButton">
        <el-button size="small" type="primary">
          <i class="el-icon-upload2"></i>
          {{ btnText }}
        </el-button>
      </slot>
      <img v-if="imageUrl && !isFile" :src="imageUrl" class="avatar" />
      <i v-if="!imageUrl && !showButton" class="el-icon-plus upload-container-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/utils'
export default {
  name: 'FileUpload',
  props: {
    isFile: {
      type: Boolean,
      default: false,
    },
    btnText: {
      type: String,
      default: '点击上传',
    },
    /**
     * 允许上传的文件类型
     */
    accept: {
      type: String,
      default: 'image/*',
    },
    imgUrl: String,
    showButton: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    imgUrl() {
      this.imageUrl = this.imgUrl
    },
  },
  data() {
    return {
      action: `${process.env.VUE_APP_API_ROOT}/file/upload`,
      headers: {
        Authorization: getToken(),
      },
      imageUrl: this.imgUrl || '',
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code === 600) {
        return this.$message.error(res.message)
      }
      this.imageUrl = res.data
      this.$emit('uploadSuccess', res, file)
    },
    beforeAvatarUpload(file) {
      if (!this.accept.split(',').includes(file.type)) {
        this.$message.error('请上传正确的类型文件!')
        return false
      }
      if (file.type.includes('image')) {
        const size = file.size / 1024 / 1024 < 2
        if (!size) {
          this.$message.error('上传图片大小不能超过2MB!')
          return false
        }
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.upload {
  &-container {
    border: 1px dashed #d9d9d9;
    width: 120px;
    height: 120px;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
    }
    .avatar {
      width: 120px;
      height: 120px;
      display: block;
    }
  }
}
</style>
